package com.wanpinghui.supplier.product;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseFragment;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.supplier.product.adapter.ProductGroupAdapter;
import com.wanpinghui.supplier.product.adapter.ProductListAdapter;
import com.wanpinghui.supplier.widgets.CountTextView;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.product.CartCountChangeListener;
import com.wanpinghui.wphlibrary.model.product.ProductService;
import com.wanpinghui.wphlibrary.model.product.bean.AddCartParamsBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductFormatBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductGroupBean;
import com.wanpinghui.wphlibrary.model.product.bean.ProductPageBean;
import com.yunshl.yunshllibrary.recyclerview.OnItemClickListener;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/12/20
 ***/
@ContentView(R.layout.layout_fragment_product_list)
public class ProductListFragment extends BaseFragment implements CartCountChangeListener {
    @ViewInject(R.id.recv_product_group)
    private RecyclerView mViewProductGroup;
    @ViewInject(R.id.recv_product_list)
    private SuperRecyclerView mViewProductList;
    @ViewInject(R.id.root_view)
    private RelativeLayout mLayoutRoot;
    @ViewInject(R.id.fl_cart)
    private FrameLayout mLayoutCartArea;
    @ViewInject(R.id.tv_cart_count)
    private CountTextView mTextViewCartCount;

    @ViewInject(R.id.tv_null)
    private TextView tv_null;

    private ProductGroupAdapter mGroupAdapter;
    private ProductListAdapter mListAdapter;
    private FormatManager formatManager;
    private PathMeasure mPathMeasure;
    private float[] mCurrentPosition = new float[2];
    private Map<Integer, ProductPageBean> dataMap;//记录获取到的产品的数据
    private Map<Integer, Integer> pageData;//记录每个产品类的产品列表的页号
    private int currentId;//当前产品类的id
    private boolean isGoCart;
    private boolean isFirstLoad = true;

    @Override
    public void init() {
        mGroupAdapter = new ProductGroupAdapter(getActivity());
        formatManager = new FormatManager(getActivity());
        dataMap = new HashMap<>();
        pageData = new HashMap<>();
        WPHSdk.addCartCountChangeListener(this);
        mViewProductGroup.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        mViewProductGroup.setAdapter(mGroupAdapter);
        mGroupAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                mGroupAdapter.setSelected(position);
                currentId = mGroupAdapter.getData(position).getId();
                if (dataMap.get(currentId) != null && dataMap.get(currentId).getPdList() != null && dataMap.get(currentId).getPdList().size() > 0) {
                    setDataView(dataMap.get(currentId));
                } else {
                    pageData.put(currentId, 1);
                    getProductList(currentId, 1);
                }
            }
        });

        mListAdapter = new ProductListAdapter(getActivity());
        mViewProductList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mViewProductList.setAdapter(mListAdapter);

        mViewProductList.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (mGroupAdapter.getItemCount() > 0) {
                    pageData.put(currentId, 1);
                    getProductList(currentId, 1);
                }else {
                    getProductTypes();
                }
            }
        });

        mListAdapter.setButtonClickListener(new ProductListAdapter.OnButtonClickListener() {
            @Override
            public void onSelectFormat(final ProductBean bean) {
                formatManager.setDatas(bean);
                formatManager.show(getActivity().findViewById(R.id.root_view));
                formatManager.setSureClick(new FormatManager.SureClick() {
                    @Override
                    public void onAddToCart(ProductBean productBean) {
                    }

                    @Override
                    public void onCreateOrder(ProductBean bean) {
                    }

                    @Override
                    public void onSure(ProductBean bean) {
                        addToCart(bean);
                    }
                });
            }

            @Override
            public void onAddCount(View view, int count) {
                addCart(view);
            }

            @Override
            public void onSelect(ProductBean bean, ProductFormatBean productFormatBean) {
                addToCart(bean);
                //CartDbManager.getInstance().addToCart(bean, productFormatBean);
            }
        });

        mListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
                intent.putExtra("id", mListAdapter.getData(position).getId());
                intent.putExtra("seller_id", mListAdapter.getData(position).getSupplier_id());
                startActivity(intent);
            }
        });

        mLayoutCartArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isGoCart = true;
                startActivity(new Intent(getActivity(), CartListActivity.class));
            }
        });

        WPHSdk.getService(ProductService.class).getCartCount(true, null);

        //initData();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isGoCart) {
            dataMap.clear();
            pageData.clear();
            if (currentId != 0) {
                pageData.put(currentId, 1);
                getProductList(currentId, 1);
            } else {
                initData();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isFirstLoad) {
            initData();
            isFirstLoad = false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //initData();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        WPHSdk.removeCartCountChangeListener(this);
    }

    public void initData() {
        getProductTypes();
    }

    private void setDataView(ProductPageBean productPageBean) {
        if (productPageBean != null && productPageBean.getPdList() != null && productPageBean.getPdList().size() > 0) {
            // mViewProductList.setVisibility(View.VISIBLE);
            tv_null.setVisibility(View.GONE);
            if (productPageBean.getCurrentPage() == 1) {
                dataMap.put(productPageBean.getPdList().get(0).getProduct_type_id(), productPageBean);
                mListAdapter.setDatas(productPageBean.getPdList());
            } else {
                ProductPageBean bean = dataMap.get(productPageBean.getPdList().get(0).getProduct_type_id());
                if (bean != null) {
                    bean.setCurrentPage(productPageBean.getCurrentPage());
                    bean.setTotalResult(productPageBean.getTotalResult());
                    bean.getPdList().addAll(productPageBean.getPdList());
                    mListAdapter.setDatas(bean.getPdList());
                }
            }
        } else {
            //       mViewProductList.setVisibility(View.GONE);

            if (productPageBean.getCurrentPage() == 1) {
                mListAdapter.setDatas(null);
                tv_null.setVisibility(View.VISIBLE);
            }
        }

        if (mListAdapter.getItemCount() >= productPageBean.getTotalResult()) {
            mViewProductList.removeMoreListener();
            mViewProductList.hideMoreProgress();
        } else {
            mViewProductList.setupMoreListener(new OnMoreListener() {
                @Override
                public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                    if (pageData.get(currentId) != null) {
                        pageData.put(currentId, pageData.get(currentId) + 1);
                    } else {
                        pageData.put(currentId, 1);
                    }
                    getProductList(currentId, pageData.get(currentId));
                }
            }, 1);
        }
    }

    private void addToCart(final ProductBean productBean) {
        List<AddCartParamsBean> list = new ArrayList<>();
        if (productBean.getFormatCount() == 0) {
            list.add(new AddCartParamsBean(productBean.getProduct_desc_id(), productBean.getCount(), null));
        } else {
            for (ProductFormatBean formatBean : productBean.getFormatList()) {
                list.add(new AddCartParamsBean(productBean.getProduct_desc_id(), formatBean.getId(), formatBean.getCount(), null));
            }
        }
        WPHSdk.getService(ProductService.class)
                .updateCart(list, new YRequestCallback() {
                    @Override
                    public void onSuccess(Object var1) {
                        productBean.setCart_item_quantity(productBean.getAllSelectCount());
                        mListAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        if (getActivity() != null) {
                            ((HomePageActivity) getActivity()).showWarningText(message);
                        }
                        productBean.resetSelectCount();
                    }

                    @Override
                    public void onException(Throwable var1) {
                        productBean.resetSelectCount();
                    }
                });
    }

    private void getProductTypes() {
        WPHSdk.getService(ProductService.class)
                .getProductTypes(new YRequestCallback<List<ProductGroupBean>>() {
                    @Override
                    public void onSuccess(List<ProductGroupBean> var1) {
                        mViewProductList.setRefreshing(false);
                        mGroupAdapter.setDatas(var1);
                        if (var1 != null && var1.size() > 0) {
                            currentId = var1.get(0).getId();
                            pageData.put(currentId, 1);
                            getProductList(currentId, 1);
                        }
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        mViewProductList.setRefreshing(false);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        mViewProductList.setRefreshing(false);
                    }
                });
    }

    private void getProductList(int groupId, int currentPage) {
        WPHSdk.getService(ProductService.class)
                .getProductList(groupId, 0, 0, currentPage, new YRequestCallback<ProductPageBean>() {
                    @Override
                    public void onSuccess(ProductPageBean var1) {
                        mViewProductList.setRefreshing(false);
                        setDataView(var1);
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        mViewProductList.setRefreshing(false);
                        //((HomePageActivity)getActivity()).showWarningText(message);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        mViewProductList.setRefreshing(false);
                        var1.printStackTrace();
                    }
                });
    }

    private void addCart(View view) {
//      一、创造出执行动画的主题---imageview
        //代码new一个imageview，图片资源是上面的imageview的图片
        // (这个图片就是执行动画的图片，从开始位置出发，经过一个抛物线（贝塞尔曲线），移动到购物车里)
        final ImageView goods = new ImageView(getContext());

        //goods.setImageDrawable(iv.getDrawable());
        goods.setBackgroundResource(R.drawable.shape_red_point);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(DensityUtil.dip2px(12), DensityUtil.dip2px(12));

        mLayoutRoot.addView(goods, params);

//        二、计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
        mLayoutRoot.getLocationInWindow(parentLocation);

        //得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        view.getLocationInWindow(startLoc);

        //得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
        mLayoutCartArea.getLocationInWindow(endLoc);


//        三、正式开始计算动画开始/结束的坐标
        //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + view.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + view.getHeight() / 2;

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        float toX = endLoc[0] - parentLocation[0] + mLayoutCartArea.getWidth() / 5;
        float toY = endLoc[1] - parentLocation[1];

//        四、计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        Path path = new Path();
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo(DensityUtil.getScreenWidth() - ((startX / 2) * ((Math.abs(toY - startY)) / (DensityUtil.getScreenHeight() - DensityUtil.dip2px(70)))), Math.abs(toY - startY) / 2, toX, toY);
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
//      五、 开始执行动画
        valueAnimator.start();

//      六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
                // 购物车的数量加1
                // 把移动的图片imageview从父布局里移除
                mLayoutRoot.removeView(goods);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    @Override
    public void onChange(int count) {
        mTextViewCartCount.setCount(count);
    }
}
